/**
 * @file 支付看板
 * @author ruanairuo(ruanairuo@baijia.com)
 * @date 2020-01-19
 */
import React, {Fragment, useState, useEffect} from 'react';
import {Space, Card, Input, Row, Col} from 'antd';

import moment from 'moment';

import {
    getResult,
    fetchSearchFormOptions
} from '~/service/shortPeriod';

import {getFirstAndLastTimestamp} from '~/utils/date';
import {numberHandle, parsePercent} from '~/utils/number';
import {convertChartListToMap} from '../../../utils/convert';

import CommonSearchBar from '../../../common/CommonSearchBar';
import EchartsLineCard from '../../../common/EchartsLineCard';
import CommonTitle from '../../../common/Title';

import {formatTooltip} from '../../../utils/formatTooltip';
import {searchForm, getDimensionId, pageId, PARTTYPE, META} from './config';

const {TextArea} = Input;

const initialValues = {
    startClassTime: getFirstAndLastTimestamp({format: 'YYYY-MM-DD'})
};


const PartThree = props => {
    const {onDetail, onDownLoad} = props;

    const [loading, setLoading] = useState(false);
    const [result2, setResult2] = useState({});
    const [result3, setResult3] = useState({});
    const [result4, setResult4] = useState({});
    const [result5, setResult5] = useState({});
    const [result6, setResult6] = useState({});
    const [result7, setResult7] = useState({});
    const [result8, setResult8] = useState({});
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState(initialValues);
    const [drilingList, setDrilingList] = useState([]);
    const [drilingLevel, setDrilingLevel] = useState(null);

    const {
        allUnitType: {
            compositeUnit = [],
            textList = []
        } = {}
    } = result2;

    const {allUnitType: {compositeUnit: compositeThree} = {}} = result3;

    const {allUnitType: {compositeUnit: compositeFour} = {}} = result4;

    const {allUnitType: {compositeUnit: compositeFive} = {}} = result5;

    const {allUnitType: {compositeUnit: compositeSix} = {}} = result6;

    const {allUnitType: {compositeUnit: compositeSeven} = {}} = result7;

    const {allUnitType: {compositeUnit: compositeEight} = {}} = result8;

    const partTwoComposite = convertChartListToMap(compositeUnit);
    const partTwoText = convertChartListToMap(textList);

    const partTwoComposite3 = convertChartListToMap(compositeThree);
    const partTwoComposite4 = convertChartListToMap(compositeFour);
    const partTwoComposite5 = convertChartListToMap(compositeFive);
    const partTwoComposite6 = convertChartListToMap(compositeSix);
    const partTwoComposite7 = convertChartListToMap(compositeSeven);
    const partTwoComposite8 = convertChartListToMap(compositeEight);

    const {[META.PART_TWO_COMPOSITE_ONE_1]: partTwoCompositeOne1} = partTwoComposite;

    const {[META.PART_TWO_COMPOSITE_TWO_1]: partTwoCompositeTwo1} = partTwoComposite3;
    const {[META.PART_TWO_COMPOSITE_TWO_2]: partTwoCompositeTwo2} = partTwoComposite4;
    const {[META.PART_TWO_COMPOSITE_TWO_3]: partTwoCompositeTwo3} = partTwoComposite5;
    const {[META.PART_TWO_COMPOSITE_TWO_4]: partTwoCompositeTwo4} = partTwoComposite6;
    const {[META.PART_TWO_COMPOSITE_TWO_5]: partTwoCompositeTwo5} = partTwoComposite7;
    const {[META.PART_TWO_COMPOSITE_TWO_6]: partTwoCompositeTwo6} = partTwoComposite8;

    const {[META.PART_TWO_TEXT_ONE]: partTwoTextOne} = partTwoText;

    // 获取全局数据
    const getData = (part, params = searchFormValues) => {
        setLoading(true);

        const {startClassTime} = params;
        const [begin, end] = startClassTime || [];
        const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
        const endRangeTime = end && moment(end).format('YYYY-MM-DD');
        params.openTime = [beginRangeTime, endRangeTime];

        getResult({...params, part}).then(res => {
            const {data} = res;

            switch (part) {
                case PARTTYPE.TWO:
                    setResult2(data);
                    break;
                case PARTTYPE.THREE:
                    setResult3(data);
                    break;
                case PARTTYPE.FOUR:
                    setResult4(data);
                    break;
                case PARTTYPE.FIVE:
                    setResult5(data);
                    break;
                case PARTTYPE.SIX:
                    setResult6(data);
                    break;
                case PARTTYPE.SEVEN:
                    setResult7(data);
                    break;
                case PARTTYPE.EIGHT:
                    setResult8(data);
                    break;
            }
        })
            .finally(() => {
                setLoading(false);
            });
    };

    const handleDetail = unit => {
        const params = {
            ...searchFormValues,
            ...unit,
            drilingList
        };

        onDetail(params);
    };

    const handleDownload = unit => {
        const params = {
            ...searchFormValues,
            ...unit,
            drilingList,
        };

        onDownLoad(params);
    };

    const handleBack = async params => {
        console.log('返回', params);
        const {unitId, unitName} = params;
        // 所有下钻取消
        setDrilingList([]);

        try {
            await getData(PARTTYPE.TWO, searchFormValues);
            await getData(PARTTYPE.THREE, searchFormValues);
            await getData(PARTTYPE.FOUR, searchFormValues);
            await getData(PARTTYPE.FIVE, searchFormValues);
            await getData(PARTTYPE.SIX, searchFormValues);
            await getData(PARTTYPE.SEVEN, searchFormValues);
            await getData(PARTTYPE.EIGHT, searchFormValues);
            // 返回搜索数据接口调用成功后level - 1
            setDrilingLevel({unitId, level: 0});
        }
        catch {}
    };

    const handleDrilling = async params => {
        console.log('下钻', params);
        const {unitId, unitName, info, dimension = {}} = params;

        const driling = {
            unitId,
            unitName,
            value: info.name,
            ...dimension
        };

        setDrilingList([driling]);

        try {
            await getData(PARTTYPE.TWO, {...searchFormValues, drilingList: [driling]});
            await getData(PARTTYPE.THREE, {...searchFormValues, drilingList: [driling]});
            await getData(PARTTYPE.FOUR, {...searchFormValues, drilingList: [driling]});
            await getData(PARTTYPE.FIVE, {...searchFormValues, drilingList: [driling]});
            await getData(PARTTYPE.SIX, {...searchFormValues, drilingList: [driling]});
            await getData(PARTTYPE.SEVEN, {...searchFormValues, drilingList: [driling]});
            await getData(PARTTYPE.EIGHT, {...searchFormValues, drilingList: [driling]});
            // 搜索接口调用成功后level + 1
            setDrilingLevel({unitId, level: 1});
        }
        catch {}
    };

    useEffect(() => {
        getData(PARTTYPE.TWO);
        getData(PARTTYPE.THREE);
        getData(PARTTYPE.FOUR);
        getData(PARTTYPE.FIVE);
        getData(PARTTYPE.SIX);
        getData(PARTTYPE.SEVEN);
        getData(PARTTYPE.EIGHT);
    }, []);

    // 表单确定
    const handleOk = fieldsValue => {
        setSearchFormValues(fieldsValue);
        setDrilingLevel(null);
        setDrilingList([]);
        getData(PARTTYPE.TWO, fieldsValue);
        getData(PARTTYPE.THREE, fieldsValue);
        getData(PARTTYPE.FOUR, fieldsValue);
        getData(PARTTYPE.FIVE, fieldsValue);
        getData(PARTTYPE.SIX, fieldsValue);
        getData(PARTTYPE.SEVEN, fieldsValue);
        getData(PARTTYPE.EIGHT, fieldsValue);
    };

    // 表单重置
    const handleReset = e => {
        setSearchFormValues(initialValues);
        setDrilingLevel(null);
        setDrilingList([]);
        getData(PARTTYPE.TWO, initialValues);
        getData(PARTTYPE.THREE, initialValues);
        getData(PARTTYPE.FOUR, initialValues);
        getData(PARTTYPE.FIVE, initialValues);
        getData(PARTTYPE.SIX, initialValues);
        getData(PARTTYPE.SEVEN, initialValues);
        getData(PARTTYPE.EIGHT, initialValues);
    };

    // 表单change
    const handleItemChange = itemKeyValue => {
        // setSearchFormValues({...searchFormValues, ...itemKeyValue});
        console.log('handleItemChange', itemKeyValue);
    };

    // 请求单个表单配置项
    const handleFetchOptions = (
        {key, searchKey, pager, dependItemKey, dependItemValue, isGetingMore, options: curOptions, fieldsValue}
    ) => {
        let permissions = searchForm.map(item => {
            if (item.key === 'startClassTime') {
                const [begin, end] = fieldsValue[item.key] || [];
                const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
                const endRangeTime = end && moment(end).format('YYYY-MM-DD');
                const filterItems = [beginRangeTime, endRangeTime];
                const dimensionId = getDimensionId(0, 'openTime');

                return (
                    {
                        dimensionId,
                        dimensionName: 'openTime',
                        filterItems
                    }
                );
            }
            return (
                {
                    dimensionId: getDimensionId(0, item.key),
                    dimensionName: item.key,
                    filterItems: fieldsValue[item.key]
                }
            );
        });

        permissions = permissions.filter(item => item.filterItems?.length);

        const params = {
            pager,
            dimensionId: getDimensionId(0, key),
            dimensionName: key,
            searchKey,
            permissions,
            unitId: pageId[0].selectID
        };

        fetchSearchFormOptions(params)
            .then(res => {
                const {data, pager} = res;

                let options = data.map(item => (
                    {
                        key: item,
                        value: item,
                        label: item
                    }
                )) || [];

                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }

                setSelectOptions({key, options, pager});
            });
    };

    return (
        <div>
            <CommonTitle
                type="subTitle"
                title="三、文曲星学情数据"
            />
            <Card style={{marginBottom: 8}}>
                <CommonSearchBar
                    loading={loading}
                    noCache
                    config={searchForm}
                    initialValues={initialValues}
                    onOk={handleOk}
                    onReset={handleReset}
                    onItemChange={handleItemChange}
                    onfetchOptions={handleFetchOptions}
                    selectOptions={selectOptions}
                />
            </Card>
            <Card style={{width: '100%'}}>
                <div className="class-previous-case">
                    <Row>
                        <EchartsLineCard
                            id={META.PART_TWO_COMPOSITE_ONE_1}
                            key={META.PART_TWO_COMPOSITE_ONE_1}
                            data={partTwoCompositeOne1}
                            loading={loading}
                            span={20}
                            title={partTwoCompositeOne1?.unitName ?? ''}
                            onBack={handleBack}
                            onDownload={handleDownload}
                            onDetail={handleDetail}
                            onDrilling={handleDrilling}
                            drilingLevel={drilingLevel}
                            grid={{left: '8%', right: '10%', bottom: 100}}
                            yAxisIndex={1}
                            unitPercentIndex={1}
                            // label={{
                            //     line: params => `${parsePercent(params.data.value)}`,
                            //     bar: params => `${numberHandle(params.data.value, 2)}`
                            // }}
                            smooth
                            part={PARTTYPE.TWO}
                            tooltip={(params => formatTooltip(params, true))}
                        />
                        <Col span={4}>
                            <TextArea
                                className="short-period-text-area"
                                style={{height: 443}}
                                value={partTwoTextOne?.textContent}
                                bordered={false}
                                readOnly
                            />
                        </Col>
                    </Row>
                </div>
                <Row>
                    <EchartsLineCard
                        id={META.PART_TWO_COMPOSITE_TWO_1}
                        key={META.PART_TWO_COMPOSITE_TWO_1}
                        data={partTwoCompositeTwo1}
                        loading={loading}
                        span={12}
                        title={partTwoCompositeTwo1?.unitName ?? ''}
                        onBack={handleBack}
                        onDownload={handleDownload}
                        onDetail={handleDetail}
                        onDrilling={handleDrilling}
                        drilingLevel={drilingLevel}
                        grid={{left: '10%', right: '15%', bottom: 100}}
                        yAxisIndex={1}
                        unitPercentIndex={1}
                        // label={{
                        //     line: params => `${parsePercent(params.data.value)}`,
                        //     bar: params => `${numberHandle(params.data.value, 2)}`
                        // }}
                        smooth
                        part={PARTTYPE.THREE}
                        tooltip={(params => formatTooltip(params, true))}
                    />
                    <EchartsLineCard
                        id={META.PART_TWO_COMPOSITE_TWO_4}
                        key={META.PART_TWO_COMPOSITE_TWO_4}
                        data={partTwoCompositeTwo4}
                        loading={loading}
                        span={12}
                        title={partTwoCompositeTwo4?.unitName ?? ''}
                        onBack={handleBack}
                        onDownload={handleDownload}
                        onDetail={handleDetail}
                        onDrilling={handleDrilling}
                        drilingLevel={drilingLevel}
                        grid={{left: '10%', right: '12%', bottom: 100}}
                        yAxisIndex={1}
                        unitPercentIndex={1}
                        // label={{
                        //     line: params => `${parsePercent(params.data.value)}`,
                        //     bar: params => `${numberHandle(params.data.value, 2)}`
                        // }}
                        smooth
                        part={PARTTYPE.SIX}
                        tooltip={(params => formatTooltip(params, true))}
                    />
                    <EchartsLineCard
                        id={META.PART_TWO_COMPOSITE_TWO_2}
                        key={META.PART_TWO_COMPOSITE_TWO_2}
                        data={partTwoCompositeTwo2}
                        loading={loading}
                        span={12}
                        title={partTwoCompositeTwo2?.unitName ?? ''}
                        onBack={handleBack}
                        onDownload={handleDownload}
                        onDetail={handleDetail}
                        onDrilling={handleDrilling}
                        drilingLevel={drilingLevel}
                        grid={{left: '10%', right: '15%', bottom: 100}}
                        yAxisIndex={1}
                        unitPercentIndex={1}
                        // label={{
                        //     line: params => `${parsePercent(params.data.value)}`,
                        //     bar: params => `${numberHandle(params.data.value, 2)}`
                        // }}
                        smooth
                        part={PARTTYPE.FOUR}
                        tooltip={(params => formatTooltip(params, true))}
                    />
                    <EchartsLineCard
                        id={META.PART_TWO_COMPOSITE_TWO_5}
                        key={META.PART_TWO_COMPOSITE_TWO_5}
                        data={partTwoCompositeTwo5}
                        loading={loading}
                        span={12}
                        title={partTwoCompositeTwo5?.unitName ?? ''}
                        onBack={handleBack}
                        onDownload={handleDownload}
                        onDetail={handleDetail}
                        onDrilling={handleDrilling}
                        drilingLevel={drilingLevel}
                        grid={{left: '10%', right: '12%', bottom: 100}}
                        yAxisIndex={1}
                        unitPercentIndex={1}
                        // label={{
                        //     line: params => `${parsePercent(params.data.value)}`,
                        //     bar: params => `${numberHandle(params.data.value, 2)}`
                        // }}
                        smooth
                        part={PARTTYPE.SEVEN}
                        tooltip={(params => formatTooltip(params, true))}
                    />
                    <EchartsLineCard
                        id={META.PART_TWO_COMPOSITE_TWO_3}
                        key={META.PART_TWO_COMPOSITE_TWO_3}
                        data={partTwoCompositeTwo3}
                        loading={loading}
                        span={12}
                        title={partTwoCompositeTwo3?.unitName ?? ''}
                        onBack={handleBack}
                        onDownload={handleDownload}
                        onDetail={handleDetail}
                        onDrilling={handleDrilling}
                        drilingLevel={drilingLevel}
                        grid={{left: '10%', right: '15%', bottom: 100}}
                        yAxisIndex={1}
                        unitPercentIndex={1}
                        // label={{
                        //     line: params => `${parsePercent(params.data.value)}`,
                        //     bar: params => `${numberHandle(params.data.value, 2)}`
                        // }}
                        smooth
                        part={PARTTYPE.FIVE}
                        tooltip={(params => formatTooltip(params, true))}
                    />
                    <EchartsLineCard
                        id={META.PART_TWO_COMPOSITE_TWO_6}
                        key={META.PART_TWO_COMPOSITE_TWO_6}
                        data={partTwoCompositeTwo6}
                        loading={loading}
                        span={12}
                        title={partTwoCompositeTwo6?.unitName ?? ''}
                        onBack={handleBack}
                        onDownload={handleDownload}
                        onDetail={handleDetail}
                        onDrilling={handleDrilling}
                        drilingLevel={drilingLevel}
                        grid={{left: '10%', right: '12%', bottom: 100}}
                        yAxisIndex={1}
                        unitPercentIndex={1}
                        // label={{
                        //     line: params => `${parsePercent(params.data.value)}`,
                        //     bar: params => `${numberHandle(params.data.value, 2)}`
                        // }}
                        smooth
                        part={PARTTYPE.EIGHT}
                        tooltip={(params => formatTooltip(params, true))}
                    />
                </Row>
            </Card>
        </div>
    );
};

export default PartThree;
